//
//  DECXPutProductsViewController.m
//  DECXInStore
//
//  Created by 程强 on 15/12/9.
//  Copyright © 2015年 程强. All rights reserved.
//

#import "DECXPutProductsViewController.h"
#import "DECXUploadPictureViewController.h"
#import "DECXManager.h"
#import "DECXCategoryListViewController.h"
#import "DECXProductOwner.h"
#import "DecimalDigitManager.h"
#import "KSPickerView.h"
#import "DECXStoreObj.h"
#import "DECXShipObj.h"
#import "DECXRegisterSeatViewController.h"

@interface DECXPutProductsViewController ()<UITextFieldDelegate,KSPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *ownerInfoBtn;
@property (weak, nonatomic) IBOutlet UIButton *onekeyRegBtn;
@property (weak, nonatomic) IBOutlet UILabel *depNameLbl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *stackNoTop;
@property (weak, nonatomic) IBOutlet UIView *depChoseView;
@property (weak, nonatomic) IBOutlet UILabel *shipNameLbl;
@property (strong, nonatomic) DECXManager *manager;
@property (strong, nonatomic) DECXPictureFile *productLogoFile;
@property (strong, nonatomic) DECXPictureFile *productOwnerFile;
@property (strong, nonatomic) DECXProductOwner *owner;
@property (strong, nonatomic) DECXCategory *choseCategory;
@property (strong, nonatomic) DecimalDigitManager *decimalManager;
@property (strong, nonatomic) NSArray *storeAry;
@property (strong, nonatomic) KSPickerView *storePicker;
@property (strong, nonatomic) DECXStoreObj *currentStore;
@property (strong, nonatomic) NSArray *shipAry;
@property (strong, nonatomic) KSPickerView *shipPicker;
@property (strong, nonatomic) DECXShipObj *selectedShip;
@property (strong, nonatomic) NSString *isPiao;
@end

@implementation DECXPutProductsViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.scrollContentSizeWidth.constant = ScreenWidth;
    
    self.manager = [DECXManager new];
    self.productLogoMarkLbl.text = @"请上传货物样品图片";
    self.productOwnerPicMarkLbl.text = @"未上传";
    self.productCategoryLbl.text = @"";
    self.isPiao = @"0";
    
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes :[ NSDictionary dictionaryWithObjectsAndKeys :
                                                                     [ UIFont systemFontOfSize:15.0 ], NSFontAttributeName ,
                                                                     [ UIColor whiteColor ], NSForegroundColorAttributeName ,
                                                                     nil ]forState : UIControlStateNormal ];
    
    _decimalManager = [DecimalDigitManager new];
    _decimalManager.decimalDigit = 2;
    self.inStoreWeightTf.delegate = _decimalManager;
    [self loadOwnerInfo];
}
- (void)loadOwnerInfo
{
    MyUser;
    if (self.inStoreType == kInStoreTypeSeat) {
        self.ownerInfoBtn.hidden = YES;
        self.onekeyRegBtn.hidden = YES;
        self.seatNoTf.text =user.seat;
        self.seatNoTf.enabled = NO;
        self.productOwnerLbl.text = user.name;
        self.productOwnerPhoneLbl.text = user.mobile.length==0?@"无":user.mobile;
        self.productOwnerTelLbl.text =user.phone.length==0?@"无":user.phone;
        self.productOwnerEmailLbl.text = user.email.length==0?@"无":user.email;
        self.stackNoTop.constant = 51;
        self.depChoseView.hidden = NO;
        self.scrollContentSizeHeight.constant = 20*50+18+10+25*5+100;

    }else{
        [self setDefaultInfo];
        self.stackNoTop.constant = 0;
        self.depChoseView.hidden = YES;
        self.scrollContentSizeHeight.constant = 19*50+18+10+25*5+100;
    }
}
- (void)setDefaultInfo
{
    MyUser;
    self.respNameTf.text = user.name;
    self.respMoblleTf.text = user.mobile;
    self.respTelTf.text = user.phone;
    self.respEmailTf.text = user.email;
    self.respAddressLbl.text = user.depot_addr;
}
- (void)loadStoreInfo:(DECXStoreObj *)obj
{
    self.currentStore = obj;
    self.respNameTf.text = obj.depotManager.name;
    self.respMoblleTf.text = obj.depotManager.mobile.length==0?@"无":obj.depotManager.mobile;
    self.respTelTf.text = obj.depotManager.phone.length==0?@"无":obj.depotManager.phone;
    self.respEmailTf.text = obj.depotManager.email.length==0?@"无":obj.depotManager.email;
    self.respAddressLbl.text = obj.depot_addr;
    self.depNameLbl.text = obj.depot_name;
}
- (void)getDepotList
{
    weak_Self(self);
    [self showMessageHUD:@"正在获取仓库列表..."];
    [[self.manager getStoreList]subscribeNext:^(id x) {
        weakSelf.storeAry = x;
        [weakSelf layoutStoreListView];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)getShipList
{
    weak_Self(self);
    [self showMessageHUD:@"正在获取船运列表..."];
    [[self.manager getShipCompanyList]subscribeNext:^(id x) {
        weakSelf.shipAry = x;
        [weakSelf layoutShipListView];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)layoutStoreListView
{
    if (!self.storePicker) {
        KSPickerView *picker = [[KSPickerView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        picker.delegate = self;
        [self.view.window addSubview:picker];
        self.storePicker = picker;
    }
    self.storePicker.dataAry = self.storeAry;
    [self.storePicker reloadData];
}
- (void)layoutShipListView
{
    if (!self.shipPicker) {
        KSPickerView *picker = [[KSPickerView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        picker.delegate = self;
        [self.view.window addSubview:picker];
        self.shipPicker = picker;
    }
    self.shipPicker.dataAry = self.shipAry;
    [self.shipPicker reloadData];
}
#pragma mark --- delegate
- (NSInteger)ksPickerView:(KSPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == self.storePicker) {
        return self.storeAry.count;
    }else if (pickerView == self.shipPicker){
        return self.shipAry.count;
    }
    return 0;
}
-(NSString*)ksPickerView:(KSPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == self.storePicker) {
        DECXStoreObj *obj = self.storeAry[row];
        return obj.depot_name;
    }else if (pickerView == self.shipPicker){
        DECXShipObj *ship = self.shipAry[row];
        return ship.ship_name;
    }
    return @"";
}
- (void)ksPickViewDidConfirmSelected:(KSPickerView *)pickerView
{
    if (pickerView == self.storePicker) {
        NSInteger row = [self.storePicker selectedRowInComponent:0];
        DECXStoreObj *obj = self.storePicker.dataAry[row];
        [self loadStoreInfo:obj];
        [self.storePicker removeFromSuperview];
        self.storePicker = nil;
    }else if (pickerView == self.shipPicker){
        NSInteger row = [self.shipPicker selectedRowInComponent:0];
        DECXShipObj *obj = self.shipPicker.dataAry[row];
        self.selectedShip = obj;
        self.shipNameLbl.text = obj.ship_name;
        [self.shipPicker removeFromSuperview];
        self.shipPicker = nil;
    }
}
- (void)ksPickerViewCancel:(KSPickerView *)pickerView
{
    if (pickerView == self.storePicker) {
        [self.storePicker removeFromSuperview];
        self.storePicker = nil;
    }else if (pickerView == self.shipPicker){
        [self.shipPicker removeFromSuperview];
        self.shipPicker = nil;
    }
}
- (IBAction)piaoHuoChange:(id)sender
{
    UISwitch *sh = sender;
    if (sh.on) {
        self.isPiao = @"1";
    }else{
        self.isPiao = @"0";
    }
}
- (IBAction)shipClick:(id)sender
{
    [self resignKeyBoard];
    if (!self.shipAry) {
        [self getShipList];
    }else{
        [self layoutShipListView];
    }
}

- (IBAction)choseDepotClick:(id)sender
{
    [self resignKeyBoard];
    if (!self.storeAry) {
        [self getDepotList];
    }else{
        [self layoutStoreListView];
    }
}
- (IBAction)commit:(id)sender
{
    [self resignKeyBoard];

    if (self.storeOrderTf.text.length == 0) {
        ToastShowInWindow(@"请输入提单号");
        return;
    }
    if (self.markTf.text.length == 0) {
        ToastShowInWindow(@"请输入唛头");
        return;
    }
    if (!self.productLogoFile) {
        ToastShowInWindow(@"请上传货物图片");
        return;
    }
    if (self.inStoreType == kInStoreTypeManager) {
        if (!self.owner) {
            ToastShowInWindow(@"请填写货权人");
            return;
        }
    }
    if (!self.productOwnerFile) {
        ToastShowInWindow(@"请上传货权图片");
        return;
    }
    if (self.inStoreWeightTf.text.length == 0) {
        ToastShowInWindow(@"请输入入库重量");
        return;
    }
    NSPredicate *pwdTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PositiveFloatRegex];
    BOOL invalied = [pwdTest evaluateWithObject:self.inStoreWeightTf.text];
    if (!invalied) {
        ToastShowInWindow(@"入库重量格式不正确");
        return;
    }
    if (self.productPlaceTf.text.length == 0) {
        ToastShowInWindow(@"请输入货物产地");
        return;
    }
    if (self.productQuanityLbl.text.length == 0) {
        ToastShowInWindow(@"请输入货物质量");
        return;
    }
    if (!self.choseCategory) {
        ToastShowInWindow(@"请选择货物种类");
        return;
    }
    if (self.stackTf.text.length == 0) {
        ToastShowInWindow(@"请输入垛位号");
        return;
    }
    if (self.inStoreType == kInStoreTypeSeat) {
        if (!_currentStore) {
            ToastShowInWindow(@"请选择入仓仓库");
            return;
        }
    }
    if (!self.selectedShip) {
        ToastShowInWindow(@"请选择船运公司");
        return;
    }
    
    DECXStoreOrderCommitModel *model = [[DECXStoreOrderCommitModel alloc] init];
    model.getlist_id = self.storeOrderTf.text;
    model.mark = self.markTf.text;
    model.img = self.productLogoFile.img;
    model.img_small = self.productLogoFile.img_small;
    model.goods_owner_prove = self.productOwnerFile.img;
    model.goods_owner_prove_small = self.productOwnerFile.img_small;
    model.inner_weight = self.inStoreWeightTf.text;
    model.goods_place = self.productPlaceTf.text;
    model.goods_type = self.choseCategory.category_id;
    model.depot_quality = self.productQuanityLbl.text;
    model.stack = self.stackTf.text;
    model.isPiao = self.isPiao;
    model.shipId = self.selectedShip.shipId;
    
    NSString *userid = @"";
    if (self.inStoreType == kInStoreTypeManager) {
        DECXUser *user = [DECXGlobal shareInstance].user;
        model.depot_responsible = user.name;
        model.depot_responsible_id = user.userid;
        model.responsible_mobile = user.mobile;
        model.responsible_phone = user.phone;
        model.responsible_email = user.email;
        model.depot_addr = user.depot_addr;
        model.depot_id = user.depot_id;
        userid = user.userid;
        
        model.goods_owner = self.owner.userid;
        model.goods_owner_mobile = self.productOwnerPhoneLbl.text;
        model.goods_owner_phone = self.productOwnerTelLbl.text;
        model.goods_owner_email = self.productOwnerEmailLbl.text;
        
    }else if (self.inStoreType == kInStoreTypeSeat){
        model.depot_responsible = self.currentStore.depotManager.name;
        model.depot_responsible_id =self.currentStore.depotManager.userid;
        model.responsible_mobile = self.currentStore.depotManager.mobile;
        model.responsible_phone = self.currentStore.depotManager.phone;
        model.responsible_email = self.currentStore.depotManager.email;
        model.depot_addr = self.currentStore.depot_addr;
        model.depot_id = self.currentStore.xid;
        userid = self.currentStore.depotManager.userid;
        MyUser;
        model.goods_owner = user.userid;
        model.goods_owner_mobile = user.mobile;
        model.goods_owner_phone = user.phone;
        model.goods_owner_email = user.email;
    }

    
    [self showHUD];
    weak_Self(self);
    [[self.manager commitStore:userid storeOrder:model]subscribeNext:^(id x) {
        ToastShowInWindow(@"货物入仓成功");
        [weakSelf gotoBack];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (IBAction)productLogoUpload:(id)sender
{
    [self resignKeyBoard];
    weak_Self(self);
    DECXUploadPictureViewController *vc = StoryBoardViewController(@"Main", @"DECXUploadPictureViewController");
    vc.uploadBlock = ^(DECXPictureFile *file){
        if (file) {
            NSLog(@"file == %@",file);
            weakSelf.productLogoFile = file;
            weakSelf.productLogoMarkLbl.text = @"已上传";
        }
    };
    vc.uploadType = UploadPictureControllerTypeProductLogo;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)productOwnerUpload:(id)sender
{
    [self resignKeyBoard];
    weak_Self(self);
    DECXUploadPictureViewController *vc = StoryBoardViewController(@"Main", @"DECXUploadPictureViewController");
    vc.uploadType = UploadPictureControllerTypeProductOwner;
    vc.uploadBlock = ^(DECXPictureFile *file){
        if (file) {
            NSLog(@"file == %@",file);
            weakSelf.productOwnerFile = file;
            weakSelf.productOwnerPicMarkLbl.text = @"已上传";
        }
    };

    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)fetchUser:(id)sender
{
    [self resignKeyBoard];
    weak_Self(self);
    [self showHUD];
    [[self.manager productOwner:self.seatNoTf.text]subscribeNext:^(id x) {
        DECXProductOwner *owner = x;
        weakSelf.owner = x;
        weakSelf.productOwnerLbl.text = owner.userTrueName;
        weakSelf.productOwnerPhoneLbl.text = owner.phone;
        weakSelf.productOwnerTelLbl.text = owner.tel;
        weakSelf.productOwnerEmailLbl.text = owner.email;
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
        weakSelf.owner = nil;
        weakSelf.productOwnerLbl.text = @"";
        weakSelf.productOwnerPhoneLbl.text = @"";
        weakSelf.productOwnerTelLbl.text = @"";
        weakSelf.productOwnerEmailLbl.text = @"";
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (IBAction)selectCategoryClick:(id)sender
{
    [self resignKeyBoard];
    weak_Self(self);
    DECXCategoryListViewController *vc = StoryBoardViewController(@"Main", @"DECXCategoryListViewController");
    vc.categoryBlock = ^(DECXCategory *category, NSString *catName){
        weakSelf.choseCategory = category;
        weakSelf.productCategoryLbl.text = catName;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)resignKeyBoard
{
    [self.storeOrderTf resignFirstResponder];
    [self.markTf resignFirstResponder];
    [self.inStoreWeightTf resignFirstResponder];
    [self.productPlaceTf resignFirstResponder];
    [self.productQuanityLbl resignFirstResponder];
    [self.stackTf resignFirstResponder];
    [self.seatNoTf resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self resignKeyBoard];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (textField == self.inStoreWeightTf) {
        NSInteger flag=0;
        
        const NSInteger limited = 2;//小数点后需要限制的个数
        
        for (NSInteger i = toBeString.length-1; i>=0; i--) {
            if ([toBeString characterAtIndex:i] == '.') {
                if (flag > limited) {
                    return NO;
                }
                break;
            }
            flag++;
        }

    }
    
    return YES;

}
- (IBAction)registerSeatClick:(id)sender
{
    DECXRegisterSeatViewController *vc = StoryBoardViewController(@"Main", @"DECXRegisterSeatViewController");
    [self.navigationController pushViewController:vc animated:YES];
    [vc registerSeatSuccess:^(DECXUser *user) {
        self.seatNoTf.text = user.seat;
//        DECXProductOwner *ow = [DECXProductOwner new];
//        ow.userid = user.userid;
//        ow.userTrueName = user.name;
//        ow.phone = user.mobile;
//        self.owner = ow;
        [self fetchUser:user.seat];
    }];
}
- (void)gotoBack
{
    [DECXGlobal shareInstance].productLogo = nil;
    [DECXGlobal shareInstance].productProve = nil;

    [super gotoBack];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
